package com.myjoje.base;

import com.myjoje.config.annotation.MapperConfig;
import com.myjoje.config.support.DaoSupport;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.util.*;

public class BaseDao {

    //常用字段(字段名请使用数据库字段名)
    protected final String FIELD_ID = "id";
    protected final String FIELD_REMARKS = "remarks";
    protected final String FIELD_CREATE_USER = "create_user";
    protected final String FIELD_MODIFY_USER = "modify_user";
    protected final String FIELD_TABLE_NAME = "tableName";
    protected final String FIELD_KEY = "key";
    protected final String FIELD_VALUE = "value";

    //表格名称
    private String tableName;
    //操作数据库对象
    private DaoSupport daoSupport;
    //mapper名称
    private String mapperName;
    //BaseMapper的名称
    private final String baseMapper = "BaseMapper";

    /**
     * 初始化属性
     */
    @PostConstruct
    public void init() throws Exception {
        Class clazz = Class.forName(this.getClass().getName());
        MapperConfig mapperConfig = (MapperConfig) clazz.getAnnotation(MapperConfig.class);
        tableName = mapperConfig.tableName();
        mapperName = mapperConfig.mapperName();
        try {
            Field field = clazz.getDeclaredField("daoSupport");
            field.setAccessible(true);
            daoSupport = (DaoSupport) field.get(this);
        } catch (Exception e) {
            e.printStackTrace();
            daoSupport = null;
        }
    }


    /**
     * 获取语句
     */
    public String getStatement(String statement) {
        return mapperName + "." + statement;
    }

    private String getBaseStatement(String statement) {
        return baseMapper + "." + statement;
    }

    /**
     * 根据id查找
     */
    public Map getById(String id) {
        Map param = getParams(FIELD_ID, id);
        return daoSupport.selectForMap(getBaseStatement("getById"), param);
    }

    /**
     * 根据id更新
     */
    public void updateById(String id, String modifyUser, Map updateMap) {
        updateById(null, id, modifyUser, updateMap);
    }

    public void updateById(String tableName, String id, String modifyUser, Map updateMap) {
        if ("".equals(id) || null == id) {
            throw new RuntimeException("[updateById] id is empty");
        }
        if (null == updateMap) {
            throw new RuntimeException("[updateById] updateMap is null");
        }
        Set keys = updateMap.keySet();
        if (updateMap.size() == 0) {
            throw new RuntimeException("[updateById] updateMap is empty");
        }
        Map map;
        //处理id和tableName
        if (null == tableName) {
            map = getParams(FIELD_ID, id);
        } else {
            map = new HashMap();
            map.put(FIELD_ID, id);
            map.put(FIELD_TABLE_NAME, tableName);
        }
        map.put(FIELD_MODIFY_USER, modifyUser);
        //更新的数据
        List list = new ArrayList();
        for (Object key : keys) {
            Map res = new HashMap();
            res.put(FIELD_KEY, key);
            res.put(FIELD_VALUE, updateMap.get(key));
            list.add(res);
        }
        map.put("list", list);
        daoSupport.update(getBaseStatement("updateById"), map);
    }

    /**
     * 根据id删除
     */
    public int deleteById(String id) {
        Map param = getParams(FIELD_ID, id);
        return daoSupport.delete(getBaseStatement("deleteById"), param);
    }


    /**
     * 获取数量
     */
    public Long getCount(Map params) {
        Map map = getParams();
        if (null != params) {
            map.putAll(params);
        }
        return (Long) daoSupport.selectForObject(getStatement("getCount"), map);
    }

    /**
     * 获取
     */

    public List get(Integer currentPage, Integer pageSize, Map... fields) {
        Map params = getParams(currentPage, pageSize, fields);
        return get(params);
    }

    protected List get(Map params) {
        return daoSupport.selectForList(getStatement("get"), params);
    }


    /**
     * 获取参数Map(包含表名)
     */
    protected Map getParams(Integer currentPage, Integer pageSize, Map... fields) {
        Map map = new HashMap();
        //添加表名
        if (!"".equals(tableName) && null != tableName) {
            map.put(FIELD_TABLE_NAME, tableName);
        }
        //处理分页数据
        if (null != currentPage && null != pageSize) {
            if (currentPage > 0 && pageSize > 0) {
                map.put("offset", ((currentPage - 1) * pageSize));
                map.put("size", pageSize);
            }
        }
        //将所有的参数放入一个map中
        for (Map field : fields) {
            if (null != field) {
                map.putAll(field);
            }
        }
        return map;
    }

    protected Map getParams() {
        Map map = new HashMap();
        //添加表名
        if (!"".equals(tableName) && null != tableName) {
            map.put("tableName", tableName);
        }
        return map;
    }

    protected Map getParams(String key, Object value) {
        Map map = getParams();
        if (null != key) {
            map.put(key, value);
        }
        return map;
    }
}